from flask import jsonify, request
from app.forms.book import SearchForm
from app.libs.myhelper import is_isbn_or_key
from app.spider.yushu_book import YuShuBook
from app.view_models.book import BookViewModel
from . import web

# 加斜杠，重定向，唯一URL原则
@web.route('/book/search')
def search():
    """
    q: 普通关键字、isbn
    page
    ?q=鲁迅&page=1
    """
    # isbn13(13个0-9的数字组成)
    # isbn10 10个0-9数字组成,含有一些'-'
    # 默认客户端传过来的是普通关键字key

    # app.add_url_rule (url, view_func=, endpoint=)
    form = SearchForm(request.args)
    if form.validate():
        q = form.q.data.strip()
        page = form.page.data
        isbn_or_key = is_isbn_or_key(q)
        # API
        if isbn_or_key == 'isbn':
            result = YuShuBook.search_by_isbn(q)
            result = BookViewModel.package_single(result, q)
        else:
            result = YuShuBook.search_by_keyword(q, page)
            result = BookViewModel.package_collection(result, q)
        # print(q, page)
        return jsonify(result)
    else:
        return jsonify(form.errors)

    # isbn_or_key = is_isbn_or_key(q)
    # if isbn_or_key == 'isbn':
    #     result = YuShuBook_V2.search_by_isbn(q)
    # else:
    #     result = YuShuBook_V2.search_by_keyword()
    # return json.dumps(result), 200, {'content-type': 'application/json'}
    # 上面的语句可以简化写成 return jsonify(result)
